<template>
  <el-dialog model-value="dialogVisible" :title="dialogTitle" width="60%" @close="handleClose" class="el-dialog">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="170px">
      <el-form-item label="工作室管理教师" prop="studioTeacherId">
        <el-select v-model="form.studioTeacherId" class="widthForm" placeholder="请选择工作室管理教师">
          <el-option v-for="item in selectTeacherList" :key="item.id" :label="item.nickname" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="工作室名称" prop="studioName">
        <el-input v-model="form.studioName" size="large" class="widthForm" />
      </el-form-item>
      <el-form-item label="工作室描述" prop="studioDes">
        <el-input v-model="form.studioDes" type="textarea" size="large" class="widthForm" />
      </el-form-item>
      <el-form-item label="工作室荣誉" prop="studioHonor">
        <!-- <el-input type="textarea" size="large" class="widthForm" /> -->

        <el-upload v-model:file-list="fileList" :action="getServerUrl() + 'sys/user/uploadImage'" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="工作室封面" prop="studioCover">
        <el-upload
          :headers="headers"
          class="avatar-uploader"
          :action="getServerUrl() + 'sys/user/uploadImage'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import requestUtil, { getServerUrl } from "@/utils/request";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { UploadProps, UploadUserFile } from "element-plus";

const tableData = ref([]);

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true,
  },
  dialogTitle: {
    type: String,
    default: "",
    required: true,
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true,
  },
});

const form = ref({
  id: -1,
  studioHonor: "",
  studioDes: "",
  studioName: "",
  studioCover: "",
  studioTeacherId: "",
});

const imageUrl = ref("");
const fileList = ref([]); // 多图

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};

// 多图

const handleAvatarSuccess = (res) => {
  imageUrl.value = getServerUrl() + res.data.src;
  form.value.studioCover = res.data.title;
};

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("图片必须是jpg格式");
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过2M!");
  }
  return isJPG && isLt2M;
};

// 用户信息下拉框
const selectTeacherList = ref([]);
const selectTeacherListFun = async () => {
  let data = {
    pageNum: 1,
    pageSize: 100,
    username: "",
  };
  const res = await requestUtil.post("sys/user/list", data);
  selectTeacherList.value = res.data.userList.records;
};

const rules = ref({
  studioTeacherId: [
    { required: true, message: "请选择管理教师", trigger: "blur" },
    { required: true, trigger: "blur" },
  ],

  studioDes: [{ required: true, message: "请输入", trigger: "blur" }],
  studioHonor: [{ required: true, message: "请输入", trigger: "blur" }],
  studioName: [{ required: true, message: "请输入", trigger: "blur" }],
});

const formRef = ref(null);

// 存入已知图片
const imagesPre = ref("[]");

const initFormData = async (id) => {
  let data = { id };
  const res = await requestUtil.get("studio/getStudioById", data);
  form.value = res.data.studio;

  imageUrl.value = getServerUrl() + "images/userAvatar/" + form.value.studioCover;
  imagesPre.value = form.value.studioHonor;
  let arr = form.value.studioHonor.split(",");

  fileList.value = [];
  arr.forEach((item, index) => {
    fileList.value.push({ url: getServerUrl() + "images/userAvatar/" + item, name: "item", title: item });
  });

  console.log(fileList);
};

watch(
  () => props.dialogVisible,
  () => {
    let id = props.id;
    if (id != -1) {
      initFormData(id);
      selectTeacherListFun();
    } else {
      fileList.value = [];
      imageUrl.value = "";
      selectTeacherListFun();
      form.value = {
        id: -1,
        studioHonor: "",
        studioDes: "",
        studioName: "",
        studioCover: "",
        studioTeacherId: "",
      };
    }
  }
);

const emits = defineEmits(["update:modelValue", "initUserList"]);

const handleClose = () => {
  emits("update:modelValue", false);
};

const handleConfirm = async () => {
  form.value.studioHonor = "";
  console.log("=========>", fileList.value);
  fileList.value.forEach((item, i) => {
    if (item.response) {
      if (i == fileList.value.length - 1) {
        form.value.studioHonor += item.response.data.title;
      } else {
        form.value.studioHonor += item.response.data.title + ",";
      }
    } else {
      if (i == fileList.value.length - 1) {
        form.value.studioHonor += item.title;
      } else {
        form.value.studioHonor += item.title + ",";
      }
    }
  });
  // form.value.studioHonor = fileList
  formRef.value.validate(async (valid) => {
    if (valid) {
      let result;
      if (form.value.id != -1) {
        result = await requestUtil.post("studio/updateStudio", form.value);
      } else {
        result = await requestUtil.post("studio/saveStudio", form.value);
      }

      let data = result.data;
      if (data.code == 200) {
        ElMessage.success(data.msg);
        formRef.value.resetFields();
        emits("initUserList");
        handleClose();
      } else {
        ElMessage.error(data.msg);
      }
    } else {
      console.log("fail");
    }
  });
};
</script>

<style scoped>
.widthForm {
  width: 100%;
}

.el-dialog {
  padding: 0 40px;
}

.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
